package com.ruoyi.framework.aspectj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.openoa.base.util.MDCLogUtil;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class TraceAspect {

    /**
     * 对使用spring amqp @StreamListener 的消费者进行增强：添加traceId，以便于对消息的消费流程进行追踪。
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(streamListener)")
    public Object consume(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MDCLogUtil.resetLogId();
            return joinPoint.proceed();
        } finally {
            MDCLogUtil.cleanLogId();
        }
    }

    /**
     * 对使用徐雪里较新版 @XxlJob 的执行者进行增强：添加traceId，以便于对消息的消费流程进行追踪。
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@annotation(xxlJob)")
    public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MDCLogUtil.resetLogId();
            return joinPoint.proceed();
        } finally {
            MDCLogUtil.cleanLogId();
        }
    }

    /**
     * 对使用@RocketMQMessageListener的消费者的onMessage()方法进行增强：添加traceId，以便于对消息的消费流程进行追踪。
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("@within(rocketMQMessageListener) && execution(* onMessage(..))")
    public Object consumeRocket(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MDCLogUtil.resetLogId();
            return joinPoint.proceed();
        } finally {
            MDCLogUtil.cleanLogId();
        }
    }

}